import json
import random
import os
import re
from typing import Optional


from .calc_helpers import calc_all_expressions


# helper functions here

cached_expressions = {}

def get_cached_expressions(point_list: list):
    global cached_expressions
    
    point_list.sort()
    keyy = json.dumps(point_list)
    
    if keyy in cached_expressions:
        return cached_expressions[keyy]
    
    expressions = calc_all_expressions(point_list)
    cached_expressions[keyy] = expressions
    return expressions


def get_random_suit() -> list:
    suit_list = ['Clubs', 'Hearts', 'Spades', 'Diamonds']
    random.shuffle(suit_list)
    return suit_list


def get_rank_str(point):
    if point == 1:
        rank = "A"
    elif point == 11:
        rank = "J"
    elif point == 12:
        rank = "Q"
    elif point == 13:
        rank = "K"
    else:
        rank = str(point)
    return rank


def get_recent_point_list(card_list):
    point_list = json.loads(card_list)["point_list"]
    return point_list


def get_random_card_list(number_list):
    suit_list = get_random_suit()
    
    cards_list = []
    for i in range(4):
        
        point = number_list[i]
        rank = get_rank_str(point)
            
        cards_list.append({"suit": suit_list[i], "rank": rank, "point": point})

    return cards_list


def extract_result(llm_resp: str) -> str:
    search_obj = re.search(r'\\boxed\{\\text\{(.*)\}\}', llm_resp, re.M | re.I)
    if search_obj is not None:
        # print(f"group 1: {search_obj.group(1)}")
        result = eval(search_obj.group(1))
        if result:
            return "Correct"

    return "Wrong"


cards_cache_file = "cards_cache.json"

def load_cards_cache() -> Optional[dict]:
    if not os.path.exists(cards_cache_file):
        return None
    
    with open(cards_cache_file,'r',encoding='utf-8') as f:
        cards_cache = json.load(f)

    return cards_cache


def save_cards_cache(last_cards_posted: str):
    cards_cache = load_cards_cache()
    if cards_cache is None:
        old_cards_arrays = []
    else:
        old_cards_arrays = cards_cache['old_cards_arrays']
    
    old_cards_arrays.append(json.loads(last_cards_posted))
    new_cards_cache = {
        "last_cards_posted": last_cards_posted,
        "old_cards_arrays": old_cards_arrays
    }

    with open(cards_cache_file,'w',encoding='utf-8') as f:
        json.dump(new_cards_cache, f,ensure_ascii=False)


def get_last_cards_posted():
    cards_cache = load_cards_cache()
    if cards_cache is None:
        last_cards_posted = ""
    else:
        last_cards_posted = cards_cache['last_cards_posted']

    return last_cards_posted


def get_old_cards_arrays():
    cards_cache = load_cards_cache()
    if cards_cache is None:
        old_cards_arrays = []
    else:
        old_cards_arrays = cards_cache['old_cards_arrays']

    return old_cards_arrays
